package com.first.wchat;

import java.io.File;
import java.util.ArrayList;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.first.wchat.data.DeviceAndGroupListener;
import com.first.wchat.data.MSGDataManager;
import com.first.wchat.data.MSGDataManager.ImageMessageData;
import com.first.wchat.data.MSGDataManager.MessageData;
import com.wchat.network.Controller;
import com.wchat.network.device.BroadCastTarget;
import com.wchat.network.device.SendTarget;
import com.wchat.util.Util;

public class BroadcastActivity extends Activity implements DeviceAndGroupListener{

	ListView mDevices;
	ListView mMessage;
	TextView mDevicesNumber;
	EditText mInput;
	Button   mSend;
	Button   mFindmage;
	Uri mUri;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.broadcast);
		initView();
		MSGDataManager.getInstance().addListener(this);
	}
	
	
	
	protected void onStart()
	{
		super.onStart();
	}

	protected void onDestroy()
	{
		MSGDataManager.getInstance().removeListener(this);
		super.onDestroy();
	}
	
	 protected void onActivityResult (int requestCode, int resultCode, Intent data) 
	    {
	    	
	    	if(requestCode == 1 && resultCode == Activity.RESULT_OK && data!= null)
	    	{
	    		mUri = data.getData();
	    		mInput.setText(mUri.toString());
	    	}
	    }
	
	private void initView()
	{

		mMessage = (ListView)findViewById(R.id.chatlist);
		mMessage.setAdapter(new MessageAdapter(MSGDataManager.getInstance().getMessage(BroadCastTarget.getInstance())));
		
		mInput = (EditText)findViewById(R.id.inputTool);
		mSend = (Button)findViewById(R.id.send);
		mSend.setOnClickListener(new MyOnClickListener());
		
		mFindmage = (Button)findViewById(R.id.findImage);
		mFindmage.setOnClickListener(new MyOnClickListener());
	}


	private class MessageAdapter extends BaseAdapter {

		ArrayList<MessageData> msgs;
		 LayoutInflater inflater ;
		public MessageAdapter(ArrayList<MessageData> message) {
			
			inflater = (LayoutInflater) BroadcastActivity.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			if(message == null)
				message = new ArrayList<MessageData>();
			msgs = message; 
		}

		public void add(MessageData md)
		{
			msgs.add(md);
		}
		@Override
		public int getCount() {
			return msgs.size();
		}

		@Override
		public Object getItem(int position) {
			return msgs.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View contentView, ViewGroup parent) {
			
			Hodler hodler ;
			if(contentView == null)
			{
				
				hodler = new Hodler();
				contentView = hodler.layout = inflater.inflate(R.layout.chat_item, null);
				contentView.setTag(hodler);
			}
			else
			{
				hodler = (Hodler)contentView.getTag();
				contentView = hodler.layout;
			}
			
			ImageView icon = (ImageView)hodler.layout.findViewById(R.id.icon);
			icon.setImageResource(R.drawable.icon);
			MessageData message = (MessageData) getItem(position);
			TextView name = (TextView)hodler.layout.findViewById(R.id.name);
			name.setText(message.getDevice().getAddress()+" : ");
			
			TextView msg = (TextView)hodler.layout.findViewById(R.id.msg);
			ImageView msg_image = (ImageView)hodler.layout.findViewById(R.id.msg_ImageS);
	    	
			if(message.isTextType())
			{

				msg_image.setVisibility(View.GONE);
				msg.setVisibility(View.VISIBLE);
				msg.setText((String)message.getMessage());
			}
			else
			{
			
				msg.setVisibility(View.GONE);

				msg_image.setVisibility(View.VISIBLE);
				msg_image.setOnClickListener(new MyOnClickListener(((ImageMessageData)message).getPath()));
				if(message.getMessage()!= null && !((Bitmap)message.getMessage()).isRecycled())
					msg_image.setBackgroundDrawable(new BitmapDrawable((Bitmap)message.getMessage()));
				else
					msg_image.setBackgroundResource(R.drawable.icon);
			}
			return contentView;
		}

	}
	
	class Hodler 
	{
		View layout;
	}
	
	class MyOnClickListener implements OnClickListener
	{

		String mPath;
		public MyOnClickListener()
		{
			
		}
		public MyOnClickListener(String filePath)
		{
			mPath = filePath;
		}
		
		@Override
		public void onClick(View v) {
			
			if(R.id.send == v.getId())
			{
				String msg = mInput.getEditableText().toString();
				if(mUri == null)
				{
					if(msg == null || msg== "")
					{
						Toast.makeText(BroadcastActivity.this, "can't send since no message!", Toast.LENGTH_SHORT).show();
						return;
					}
					MSGDataManager.getInstance().addMessage(BroadCastTarget.getInstance(), Controller.getInstance().getDeviceContext().getLocal(),msg,null);
					MainActivity.getUserAction().sendText(msg, BroadCastTarget.getInstance());
				}
				else
				{
					String path = Util.getUriFilePath(BroadcastActivity.this, mUri);
					File imageFile = new File(path);
					MSGDataManager.getInstance().addMessage(BroadCastTarget.getInstance(), Controller.getInstance().getDeviceContext().getLocal(),Util.getScaleBitmap(imageFile),imageFile.getAbsolutePath());
					MainActivity.getUserAction().sendImage(imageFile, BroadCastTarget.getInstance());
					mUri = null;
				}
				mInput.clearComposingText();
				mInput.setText("");
			}
			else if(R.id.findImage == v.getId())
			{
				Intent intent = new Intent();
				intent.setAction(android.content.Intent.ACTION_GET_CONTENT);
				intent.setType("image/*");
				BroadcastActivity.this.startActivityForResult(intent, 1);
			}
			else if(R.id.msg_ImageS == v.getId())
			{
				
				if(mPath.contains("/mnt/"))
					mPath = mPath.replace("/mnt/", "/");
				if(!mPath.startsWith("file://"))
					mPath = "file://"+mPath;
				Uri uri = Uri.parse(mPath);
				Intent intent = new Intent(Intent.ACTION_VIEW);
				intent.setDataAndType(uri, "image/*");
				BroadcastActivity.this.startActivity(intent);
			}
			
			
		}
		
	}

	
	@Override
	public void newMessage(SendTarget target, Object o) {
		initView();
		
	}



	@Override
	public void newMessage(SendTarget group, SendTarget target, Object o) {
		initView();
		
	}



	@Override
	public void Join(SendTarget target) {
		initView();
		
	}



	@Override
	public void leave(SendTarget target) {
		initView();
		
	}

}
